<template>
  <div class="supplier-info-container">
    <!-- 基本信息部分 -->
    <div class="info-section">
      <div class="section-title">基本信息</div>

      <div class="form-item">
        <div class="form-label required">店铺名</div>
        <div class="form-value">
          <input
            type="text"
            class="form-input"
            v-model="addStoreInfo.name"
            placeholder="请输入店铺名"
          />
        </div>
      </div>

      <div class="form-item">
        <div class="form-label">店长名</div>
        <div class="form-value">
          <input
            type="text"
            class="form-input"
            v-model="addStoreInfo.store_manager_name"
            placeholder="请输入店长名"
          />
        </div>
      </div>

      <div class="form-item">
        <div class="form-label">邮件地址</div>
        <input
          type="text"
          class="form-input"
          placeholder="请输入您的邮件地址"
          v-model="addStoreInfo.email_address"
        />
      </div>

      <div class="form-item">
        <div class="form-label required">联系电话</div>
        <input
          type="tel"
          class="form-input"
          placeholder="请输入您的联系电话"
          v-model="addStoreInfo.mobile"
        />
      </div>

      <div class="form-item">
        <div class="form-label required">登录手机号</div>
        <input
          type="tel"
          class="form-input"
          placeholder="请输入您的登录手机号"
          v-model="addStoreInfo.account"
        />
      </div>

      <div class="form-item">
        <div class="form-label required">登录密码</div>
        <input
          type="tel"
          class="form-input"
          placeholder="请输入您的登录密码"
          v-model="addStoreInfo.password"
        />
      </div>

      <div class="form-item">
        <div class="form-label required">所属地区</div>
        <div class="form-select" @click="selectRegion">
          <text class="form-select-text">{{
            (addStoreInfo.region && addStoreInfo.region.join("-")) ||
            "请选择省-市-区"
          }}</text>
          <text class="gui-block-text gui-icons select-arrow">&#xe69e;</text>
        </div>
      </div>

      <div class="form-item" @click="getLocation">
        <div class="form-label required">详细地址</div>
        <text class="form-select-text address-text">{{
          addStoreInfo.address
        }}</text>
        <div class="location-btn">定位</div>
      </div>
    </div>

    <!-- 证件上传部分 -->
    <div class="upload-section">
      <div class="section-title">上传证件</div>
      <div class="upload-item">
        <div class="upload-label">营业执照</div>
        <div class="upload-content">
          <div
            class="upload-preview"
            v-if="addStoreInfo.business_license"
            @click.stop="previewImg('business_license')"
          >
            <gui-image
              :width="160"
              :height="160"
              :src="addStoreInfo.business_license"
              class="preview-img"
              mode="cover"
            ></gui-image>
            <div
              class="delete-btn"
              @click.stop="deleteImage('business_license')"
            >
              <span class="delete-icon">×</span>
            </div>
          </div>
          <div
            class="upload-btn"
            v-else
            @click="uploadImage('business_license')"
          >
            <div class="upload-icon">+</div>
            <div class="upload-text">上传照片</div>
          </div>
        </div>
      </div>

      <div class="upload-item">
        <div class="upload-label">店铺logo</div>
        <div class="upload-content">
          <div
            class="upload-preview"
            v-if="addStoreInfo.logo"
            @click.stop="previewImg('logo')"
          >
            <gui-image
              :width="160"
              :height="160"
              :src="addStoreInfo.logo"
              class="preview-img"
              mode="cover"
            />
            <div class="delete-btn" @click.stop="deleteImage('logo')">
              <span class="delete-icon">×</span>
            </div>
          </div>
          <div class="upload-btn" v-else @click="uploadImage('logo')">
            <div class="upload-icon">+</div>
            <div class="upload-text">上传照片</div>
          </div>
        </div>
      </div>
    </div>
    <gui-area-picker
      :value="addStoreInfo.region"
      ref="areaPickerRef"
      @confirm="confirmRegion"
    />

    <!-- 保存按钮 -->
    <div class="save-btn-container">
      <button class="save-btn" @click="saveInfo">保存</button>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { onShow, onLoad } from "@dcloudio/uni-app";
import { showToast } from "@/utils/helper";
import { upLoadOss } from "@/api/common";
import {
  shopRegister,
  getOpenId,
  checkOpenIdisCreat,
  getShopInfo,
  shopRegisterEdit,
} from "@/api/login";
import { setToken, clearToken } from "@/utils/vmeitime-http/localStorage";
import { getLocationByGaode } from "@/utils/helper";
const copy = () => {
  uni.setClipboardData({
    data: code.value,
    success: function () {
      showToast("复制成功");
    },
  });
};

// 店铺入驻信息数据
const addStoreInfo = ref({
  supplier_info_id: "",
  name: "",
  store_manager_name: "",
  email_address: "",
  account: "",
  password: "",
  mobile: "",
  region: [],
  province: "",
  city: "",
  area: "",
  lng: "",
  lat: "",
  address: "",
  business_license: "",
  logo: "",
  openid: undefined,
});

const rules = ref({
  name: {
    required: true,
    msg: "请输入店铺名称",
  },
  // store_manager_name: {
  //   required: true,
  //   msg: "请输入店长名",
  // },
  mobile: {
    required: true,
    msg: "请输入联系电话",
    other: /^1[3-9]\d{9}$/,
    otherMsg: "请输入正确的联系电话",
  },
  account: {
    required: true,
    msg: "请输入账号",
  },
  password: {
    required: true,
    msg: "请输入密码",
  },
  region: {
    required: true,
    msg: "请选择所属地区",
  },
  address: {
    required: true,
    msg: "请输入详细地址",
  },
  // business_license: {
  //   required: true,
  //   msg: "请上传营业执照",
  // },
  // logo: {
  //   required: true,
  //   msg: "请上传店铺logo",
  // },
});

const areaPickerRef = ref(null);
// 选择地区
const selectRegion = () => {
  // 这里可以调用地区选择器
  areaPickerRef.value.open();
};

// 获取位置
const getLocation = () => {
  uni.chooseLocation({
    type: "gcj02",
    latitude: addStoreInfo.value.lat,
    longitude: addStoreInfo.value.lng,
    success: (res) => {
      addStoreInfo.value.address = res.address;
      addStoreInfo.value.lat = res.latitude;
      addStoreInfo.value.lng = res.longitude;
    },
  });
};

// 上传图片
const uploadImage = (type) => {
  uni.chooseImage({
    count: 1,
    success: async (res) => {
      // 显示上传中
      const suffix = res.tempFilePaths[0].split(".");
      const imgArr = ["jpg", "jpeg", "png"];
      if (!imgArr.includes(suffix[1])) {
        showToast("请上传图片格式为jpg,jpeg,png的图片");
        return;
      }
      uni.showLoading({
        title: "上传中...",
      });
      upLoadOss(res.tempFilePaths[0])
        .then((value) => {
          addStoreInfo.value[type] = value;
          uni.hideLoading();
        })
        .catch((err) => {
          uni.hideLoading();
          showToast(err.message);
        });
    },
    fail: (e) => {
      console.log("上传失败", e);
    },
  });
};

const previewImg = (type) => {
  uni.previewImage({
    urls: [addStoreInfo.value[type]],
  });
};

// 删除图片
const deleteImage = (type) => {
  addStoreInfo.value[type] = "";
};

const checkRules = () => {
  for (let key in rules.value) {
    if (rules.value[key].required && !addStoreInfo.value[key]) {
      showToast(rules.value[key].msg);
      return false;
    } else if (rules.value[key].required && addStoreInfo.value[key]) {
      if (
        rules.value[key].other &&
        !rules.value[key].other.test(addStoreInfo.value[key])
      ) {
        showToast(rules.value[key].otherMsg);
        return false;
      }
    }
  }
  return true;
};
// 保存信息
const saveInfo = async () => {
  const res = checkRules();
  if (!res) return;
  console.log("保存信息", addStoreInfo.value);
  if (!addStoreInfo.value.logo) {
    addStoreInfo.value.logo =
      "https://cphimg.leyoo888.com/dev/upload/supplier/2025-06-26/1750932052933.jpeg";
  }
  const ress = edit.value
    ? await shopRegisterEdit(addStoreInfo.value)
    : await shopRegister(addStoreInfo.value);
  showToast("注册成功，请等待审核");
  setTimeout(() => {
    uni.redirectTo({
      url: "/pages/login/storeAuditInfo?audit_status=1",
    });
  }, 800);
};

const confirmRegion = (res) => {
  addStoreInfo.value.region = res.names;
  addStoreInfo.value.province = res.names[0];
  addStoreInfo.value.city = res.names[1];
  addStoreInfo.value.area = res.names[2];
};
const code = ref("");
const getCode = () => {
  return new Promise((resolve) => {
    uni.login({
      provider: "weixin",
      success: (res) => {
        getOpenId({ code: res.code })
          .then((ress) => {
            resolve(ress.openid);
          })
          .catch((err) => {
            showToast(err);
          });
      },
    });
  });
};
const edit = ref(0);
const checkjudge = async (options) => {
  const res = await checkOpenIdisCreat({
    openid: addStoreInfo.value.openid,
    supplier_info_id: addStoreInfo.value.supplier_info_id,
  });
  if (res.is_register === 1) {
    await setToken(res.token);
    getShopInfo({
      openid: addStoreInfo.value.openid,
      supplier_info_id: addStoreInfo.value.supplier_info_id,
    }).then((res) => {
      console.log(res);
      if (edit.value == 1) {
        addStoreInfo.value = {
          ...res,
          openid: addStoreInfo.value.openid,
          supplier_info_id: addStoreInfo.value.supplier_info_id,
        };
        addStoreInfo.value.region = [
          addStoreInfo.value.province,
          addStoreInfo.value.city,
          addStoreInfo.value.area,
        ];
        return;
      }
      uni.redirectTo({
        url: `/pages/login/storeAuditInfo?audit_status=${res.audit_status}&audit_remarks=${res.audit_remarks}&supplier_info_id=${addStoreInfo.value.supplier_info_id}`,
      });
    });
  } else {
    // 没注册过，给默认设置一个经纬度  防止ios打不开
    try {
      const { latitude, longitude } = await getLocationByGaode();
      addStoreInfo.value.lat = latitude;
      addStoreInfo.value.lng = longitude;
    } catch (err) {
      showAuthModal();
    }
  }
};

// 显示授权提示弹窗
const showAuthModal = () => {
  uni.showModal({
    title: "位置信息授权",
    content:
      "需要获取您的位置信息才能为您提供周边供应商服务，请授权获取位置信息",
    confirmText: "去授权",
    cancelText: "退出应用",
    success: (res) => {
      if (res.confirm) {
        // 打开设置页面让用户手动开启授权
        uni.openSetting({
          success: (settingRes) => {
            if (settingRes.authSetting["scope.userLocation"]) {
              // 用户在设置页面中同意授权
              getLocation();
            } else {
              // 用户仍然拒绝授权，再次提示
              uni.showToast({
                title: "未授权位置信息，无法使用本应用",
                icon: "none",
                duration: 2000,
                complete: () => {
                  setTimeout(() => {
                    showAuthModal(); // 再次显示授权弹窗，形成循环
                  }, 2000);
                },
              });
            }
          },
        });
      } else {
        wx.exitMiniProgram({ success: (res) => {} });
      }
    },
    // 防止用户通过点击遮罩层关闭弹窗
    maskClosable: false,
  });
};

onLoad(async (options) => {
  const res = await getCode();
  edit.value = options.edit || 0;
  addStoreInfo.value.openid = res;
  addStoreInfo.value.supplier_info_id = options.id;
  // 判断一下这个opid是不是已经注册过了  然后请求一下接口获取详情
  checkjudge(options);
});
</script>

<style scoped>
.supplier-info-container {
  background-color: #f5f5f5;
  padding-bottom: 40rpx;
}

/* 基本信息部分样式 */
.info-section,
.upload-section {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 0 30rpx;
}

.section-title {
  color: #0066ff;
  font-size: 28rpx;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;
}

.form-item {
  display: flex;
  padding: 30rpx 0;
  border-bottom: 1px solid #eee;
  position: relative;
}

.form-label {
  width: 180rpx;
  font-size: 28rpx;
  color: #333;
}

.required::before {
  content: "*";
  color: #ff0000;
  margin-right: 4rpx;
}

.form-value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.form-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  height: 40rpx;
  border: none;
}

.form-select {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-select-text {
  font-size: 28rpx;
  color: #999;
}

.select-arrow {
  font-size: 24rpx;
  color: #999;
}

.location-btn {
  position: absolute;
  right: 0;
  top: 30rpx;
  color: #0066ff;
  font-size: 28rpx;
}

/* 上传部分样式 */
.upload-item {
  padding: 30rpx 0;
  border-bottom: 1px solid #eee;
}

.upload-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.upload-content {
  display: flex;
}

.upload-btn {
  width: 160rpx;
  height: 160rpx;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border: 1px dashed #ddd;
}

.upload-icon {
  font-size: 48rpx;
  color: #ccc;
  margin-bottom: 10rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #999;
}

.upload-preview {
  width: 160rpx;
  position: relative;
}

.preview-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-btn {
  position: absolute;
  top: -14rpx;
  right: -8rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: #f00;
  color: #fff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24rpx;
}

.delete-icon {
  font-size: 30rpx;
  color: #fff;
  position: absolute;
  top: -1px;
}

/* 保存按钮样式 */
.save-btn-container {
  padding: 12rpx 30rpx;
}

.save-btn {
  width: 100%;
  height: 90rpx;
  background-color: #0066ff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border: none;
}

.address-text {
  flex: 1;
  margin-right: 60rpx;
}
</style>
